package bloggo

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type HandlerFunc func(c *gin.Context) *R

var Wrapper func(handler HandlerFunc) func(c *gin.Context) = wrapper

//Wrapper 包装一层HandlerFunc
func wrapper(handler HandlerFunc) func(c *gin.Context) {
	return func(c *gin.Context) {
		code := http.StatusOK
		defer func(c *gin.Context) {
			DelSessionUser()
			err := recover() // recover()内置函数，可以捕获到异常
			if err != nil {
				Log(fmt.Sprintf("%v", err))
				code = http.StatusInternalServerError
				c.JSONP(code, FailMessage(fmt.Sprintf("%v", err)))
			}
		}(c)
		r := handler(c)
		if r == nil {
			r = UnknownErr()
		}
		if !r.Flag {
			code = http.StatusInternalServerError
		}
		r.Request = c.Request.Method + " " + c.Request.URL.String()
		c.JSONP(code, r)
	}
}
